#include "map_tool/RayTool.h"
#include "map_minedataset/MineDataSet.h"
#include "osgGA/TrackballManipulator"
#include "osg/Array"
#include <iostream>

namespace Tool
{
	CPointSelectTool::CPointSelectTool()
	{

	}

	CPointSelectTool::~CPointSelectTool()
	{

	}

	bool CPointSelectTool::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
	{
		bool result = false;
		osg::Vec3d r(0, 0, 0);
		osgViewer::Viewer* pViewer = dynamic_cast<osgViewer::Viewer*>(&aa);
		if (NULL == pViewer)
			return result;
		float ex = ea.getX();
		float ey = ea.getY();
		//switch (ea.getEventType())
		{
		//case(osgGA::GUIEventAdapter::PUSH) :

			if (ea.getEventType() == osgGA::GUIEventAdapter::RELEASE
				&& ea.getButton() == 1)
			{
				osgUtil::LineSegmentIntersector::Intersections intersections;
				if (pViewer->computeIntersections(ea, intersections))
				{
					for (osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin();
						hitr != intersections.end();
						++hitr)
					{
						osgUtil::LineSegmentIntersector::Intersection intersection = (*hitr);
						osg::NodePath& nodePath = intersection.nodePath;
						for (int i = nodePath.size() - 1; i >= 0; --i)
						{
							osg::ref_ptr<osg::Node> node = dynamic_cast<osg::Node *>(nodePath[i]);
							if (NULL != node)
							{
								DataRender::CRenderNode* pRenderNode =
									dynamic_cast<DataRender::CRenderNode*>(node.get());
								if (pRenderNode && pRenderNode->Owner)
								{
									CSelectEvent evt;
									evt.SelectObject = pRenderNode->Owner;
									this->notifyHandlers(&evt);
									result = true;
									return result;
								}
							}
						}
					}
				}
			}
			//break;
		}
		
		return result;
	}

}